package cn.gok.reflect;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName 反射获取不同类的实例对象
 * @Description TODO
 * @Author HP
 * @Date 15:09 2022/7/12
 * @Version 1.0
 **/

public class 反射获取不同类的实例对象 {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
        运行期获得实例对象();
        //反射破坏();
        //破坏成员方法的封装性();


    }

    private static void 破坏成员方法的封装性() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class c = A.class;
        A a = new A();
        Method m = c.getDeclaredMethod("doTest",String.class,Float.class);
        m.setAccessible(true);
        m.invoke(a,"aaa",100f);


    }

    private static void 反射破坏() throws NoSuchFieldException, IllegalAccessException {
        A a = new A();
        Class c =A.class;
        Field f1 = c.getDeclaredField("x");
        f1.setAccessible(true);
        f1.set(a,1000);
        System.out.println(f1.get(a));

    }

    private static void 运行期获得实例对象() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class c = A.class;
        A a =(A)c.newInstance();
        a.fly();

        Constructor con = c.getConstructor(int.class);
        A a2= (A) con.newInstance(100);
        System.out.println(a2.getX());


    }
}
